//
//  HomeCollectionView.swift
//  SwiftStory
//
//  Created by ZxjMacBookPro on 2020/6/21.
//  Copyright © 2020 ZxjMacBookPro. All rights reserved.
//

import UIKit
import SDWebImage

class HomeCollectionView: UICollectionView, UICollectionViewDataSource, UICollectionViewDelegate{
    
    /// 配图高度约束
    @IBOutlet weak var pictureCollectionViewHeightCons: NSLayoutConstraint!
    // 配图宽度约束
    @IBOutlet weak var pictureCollectionViewWidthCons: NSLayoutConstraint!
    /// 配图布局对象
    @IBOutlet weak var flowLayout: UICollectionViewFlowLayout!
    
    /// 模型数据
    var viewModel: StatusViewModel?
    {
        didSet{
            // 8.更新配图
            reloadData()
            
            // 9.跟新配图尺寸
            let (itemSize, clvSize) = calculateSize()
            // 9.1更新cell的尺寸
            if itemSize != CGSize.zero
            {
                flowLayout.itemSize = itemSize
            }
            // 9.2跟新collectionView尺寸
            pictureCollectionViewHeightCons.constant = clvSize.height
            pictureCollectionViewWidthCons.constant = clvSize.width
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        self.dataSource = self
        self.delegate = self
    }
    
    // MARK: - UICollectionViewDataSource
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel?.thumbnail_pic?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "pictureCell", for: indexPath) as! HomePictureCell
        cell.backgroundColor = UIColor.red
        
        cell.url = viewModel!.thumbnail_pic![indexPath.item]
        
        return cell
    }
    
    // MARK: - UICollectionViewDelegate
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
//        let url = viewModel?.thumbnail_pic![indexPath.item]
        
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: ZXJShowPhotoBrowserController), object: self, userInfo: ["bmiddle_pic": viewModel!.bmiddle_pic!, "indexPath": indexPath])
    }
    
    // MARK: - 内部控制方法
    /// 计算cell和collectionview的尺寸
    private func calculateSize() -> (CGSize, CGSize){
        /*
         没有配图: cell = zero, collectionview = zero
         一张配图: cell = image.size, collectionview = image.size
         四张配图: cell = {90, 90}, collectionview = {2*w+m, 2*h+m}
         其他张配图: cell = {90, 90}, collectionview =
         */
        let count = viewModel?.thumbnail_pic?.count ?? 0
        // 没有配图
        if count == 0
        {
            return (CGSize.zero, CGSize.zero)
        }
        
        // 一张配图
        if count == 1
        {
            let key = viewModel!.thumbnail_pic!.first!.absoluteString
            // 从缓存中获取已经下载好的图片, 其中key就是图片的url
            
            let image = SDImageCache.shared.imageFromCache(forKey: key)
            
            return (image!.size, image!.size)
        }
        
        //        let imageWidth: CGFloat = 90
        //        let imageHeight: CGFloat = 90
        let imageMargin: CGFloat = 10
        // 四张配图
        if count == 4
        {
            let col = 2
            let row = col
            // 宽度 = 图片的宽度 * 列数 + (列数 - 1) * 间隙
            var screenWidth = UIScreen.main.bounds.size.width - 20
            let width = (screenWidth  - CGFloat(col) * imageMargin ) / CGFloat(3)
            screenWidth = screenWidth - width - imageMargin
            
            //            let width = imageWidth * CGFloat(col) + CGFloat(col - 1) * imageMargin
            // 宽度 = 图片的高度 * 行数 + (行数 - 1) * 间隙
            let height = width * CGFloat(row) + CGFloat(row - 1) * imageMargin
            //            let height = imageHeight * CGFloat(row) + CGFloat(row - 1) * imageMargin
            NSLog(message: "\(CGSize(width: width, height: width)) , \(CGSize(width: screenWidth, height: height))")
            return (CGSize(width: width, height: width), CGSize(width: screenWidth, height: height))
        }
        
        // 其他张配图
        let col = 3
        let row = (count - 1) / 3 + 1
        // 宽度 = 图片的宽度 * 列数 + (列数 - 1) * 间隙
        let screenWidth = UIScreen.main.bounds.size.width - 20
        let width = (screenWidth  - CGFloat(col - 1) * imageMargin ) / CGFloat(col)
        // 宽度 = 图片的高度 * 行数 + (行数 - 1) * 间隙
        //        let height = imageHeight * CGFloat(row) + CGFloat(row - 1) * imageMargin
        let height = width * CGFloat(row) + CGFloat(row - 1) * imageMargin
        return (CGSize(width: width, height: width), CGSize(width: screenWidth, height: height))
    }
}

class HomePictureCell: UICollectionViewCell {
    
    var url: URL?{
        didSet{
            customIconImageView.sd_setImage(with: url, completed: nil)
        }
    }
    
    lazy var customIconImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.clipsToBounds = true
        imageView.contentMode = .scaleAspectFill
        self.contentView.addSubview(imageView)
        imageView.mas_makeConstraints { (make) in
            make?.edges.equalTo()(contentView)
        }
        return imageView
    }()
    
}
